package com.huike.springboot1.demos.controller;

import com.huike.springboot1.demos.pojo.User1;
import com.huike.springboot1.demos.service.MailService;
import com.huike.springboot1.demos.service.User1Service;
import com.huike.springboot1.demos.utils.VerifyCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.Collections;

@Controller
public class RegisterController {
    @Autowired
    private User1Service userService;
    @Autowired
    private MailService mailService;

    // 跳转注册页
    @GetMapping("/register")
    public String toRegister(Model model) {
        model.addAttribute("user", new User1()); // 复用User1实体
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
//        return "user/register";
        return "register";
    }

    // 发送验证码
    @PostMapping("/sendCode")
    @ResponseBody
    public String sendCode(@RequestParam String email, HttpSession session) {
        try {
            if (userService.existsByEmail(email)) {
                return "邮箱已注册";
            }
            String code = VerifyCodeUtil.generateCode();
            VerifyCodeUtil.storeCode(session, email, code);
            mailService.sendVerifyCode(email, code);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();   // 显示错误日志
            return "发送失败";
        }
    }

    // 提交注册（无数据校验）
    @PostMapping("/doRegister")
    public String doRegister(
            User1 user, // 复用User实体接收参数
            @RequestParam String verifyCode,
            HttpSession session,
            RedirectAttributes redirect
    ) {
        try {
            // 检查用户名是否存在
            if (userService.findByUsername(user.getUsername()) != null) {
                redirect.addFlashAttribute("error", "用户名已存在");
                return "redirect:/register";
            }

            // 检查邮箱是否存在
            if (userService.existsByEmail(user.getEmail())) {
                redirect.addFlashAttribute("error", "邮箱已注册");
                return "redirect:/register";
            }

            // 验证验证码
            if (!VerifyCodeUtil.validateCode(session, user.getEmail(), verifyCode)) {
                redirect.addFlashAttribute("error", "验证码错误或过期");
                return "redirect:/register";
            }

            // 注册用户（加密密码+默认角色）
            user.setStatus(1); // 启用状态
            userService.add(user, Collections.singletonList(2L)); // 关联USER角色（ID=2）

            redirect.addFlashAttribute("msg", "注册成功，请登录");
            return "redirect:/toLogin";
        } catch (Exception e) {
            redirect.addFlashAttribute("error", "注册失败");
            return "redirect:/register";
        }
    }
}
